import changeCity from "../../component/changeCity/index.vue";
import AddPost from "./addPost/addPost.vue";
export default {
  name: "systemManage",
  // components: {
  //   userManage: () => import('./userManage/userManage.vue'),
  //   roleManage: () => import('./roleManage/roleManage.vue'),
  // },
  components: {
    changeCity,
    AddPost
  },
  data() {
    return {
      show: true, //待办，日志列表组件切换
      backBtn: false,
      activeIndex: 0,
      activeName: "岗位角色管理",
      options: [
        {
          title: "岗位角色管理",
          show: false
        },
        {
          title: "操作人员管理",
          show: false
        }
      ],
      addUserIsVisible: false,
      addRoleIsVisible: false,
      AddPostShow: false,
      manage: "新增",
      addUserForm: {
        acuserid: "",
        name: "",
        account: "",
        telnum: "",
        department: "",
        departmentid: "",
        citys: [],
        province: "", //省份编码
        city: "", //城市编码
        area: "" //区域编码
      },
      level: "", //级别
      roleLevel: {
        index: ""
      },
      pages: {
        pagesize: 10,
        total: 0,
        pagenum: 1
      },
      roleLevelOptions: [
        {
          title: "平台管理",
          type: "0"
        },
        {
          title: "省级管理员",
          type: "1"
        },
        {
          title: "市级管理员",
          type: "2"
        },
        {
          title: "区县管理员",
          type: "3"
        }
      ], // 部门列表
      addRoleForm: {
        departmentid: "",
        department: "", // 部门
        position: "", // 岗位
        rolelist: [] // 权限列表(只包含权限id)
      },
      selectedRole: [], // 权限名称(只包含权限名称)
      departmentOptions: [], // 部门列表
      authorities: [], //权限列表
      dashboardid: "",

      userManageData: [],
      loading: false,

      userTotal: 0,
      userPageSize: 10,
      userCurrentPage: 1,

      roleManageData: [],
      roleTotal: 0,
      rolePageSize: 10,
      roleCurrentPage: 1,
      allRolelist: [],
      currentStatus: "", //1新增 2//编辑
      global: {},
      tabs: [],
      useridlist: [""],
      xiazuan_backBtn: false

      //待办事项
    };
  },
  created() {
    this.global = this.GLOBAL;
    let permisstions = this.GLOBAL.permisstions;
    permisstions.forEach(item => {
      if (item.power == 12) {
        this.tabs = item.tablelist;
        this.tabs.forEach(items => {
          if (items.table == "1201") {
            this.options[1].show = true;
          } else if (items.table == "1202") {
            this.options[0].show = true;
          }
        });
      }
    });
    if (!this.options[0].show && this.options[1].show) {
      this.activeIndex = 1;
      this.activeName = this.options[1].title;
    }

    this.getroleData();
    this.getpostData();
    this.getroleManageData();
    this.getUserManageData();
    this.getAuthority();
  },
  computed: {
    postOptions: function() {
      for (let i = 0; i < this.departmentOptions.length; i++) {
        if (
          this.departmentOptions[i].department === this.addUserForm.department
        ) {
          return this.departmentOptions[i].list;
        }
      }
    }
  },
  methods: {
    // 切换tab栏
    selected(item, index) {
      this.show = true;
      this.backBtn = false;
      this.activeName = item;
      this.activeIndex = index;
    },
    // 获取用户列表数据
    getUserManageData() {
      this.loading = true;
      this.$axios
        .post("/system/v1/platform/user/list", {
          pagenum: this.userCurrentPage,
          pagesize: this.userPageSize
        })
        .then(res => {
          if (res.data.message === "success.") {
            this.userManageData = res.data.data.list;
            this.userTotal = parseInt(res.data.data.totalnum);
            this.loading = false;
          }
        })
        .catch({});
    },
    //下钻
    xiazuan(row) {
      this.userCurrentPage = 1;
      this.userPageSize = 10;
      this.useridlist.push(row.userid);
      this.loading = true;
      this.$axios
        .post("/system/v1/platform/user/list", {
          userid: row.userid,
          pagenum: this.userCurrentPage,
          pagesize: this.userPageSize
        })
        .then(res => {
          if (res.data.message === "success.") {
            this.userManageData = res.data.data.list;
            this.userTotal = parseInt(res.data.data.totalnum);
            this.loading = false;
          }
        });
    },
    //下钻返回按钮
    goBack_xiazuan() {
      this.userCurrentPage = 1;
      this.userPageSize = 10;
      this.useridlist.pop();
      this.loading = true;
      this.$axios
        .post("/system/v1/platform/user/list", {
          userid: this.useridlist[this.useridlist.length],
          pagenum: this.userCurrentPage,
          pagesize: this.userPageSize
        })
        .then(res => {
          if (res.data.message === "success.") {
            this.userManageData = res.data.data.list;
            this.userTotal = parseInt(res.data.data.totalnum);
            this.loading = false;
          }
        });
    },
    // 获取角色列表数据
    getroleManageData() {
      this.loading = true;
      this.$axios
        .$post("/system/v1/platform/department/list", {
          pagenum: this.roleCurrentPage,
          pagesize: this.rolePageSize
        })
        .then(res => {
          if (res.data.message === "success.") {
            this.roleTotal = parseInt(res.data.data.totalnum);
            // this.rolePageSize = parseInt(res.data.data.totalnum)
            this.roleManageData = res.data.data.list;
            this.loading = false;
          }
        });
    },
    // 实现用户列表分页
    userHandleCurrentChange(val) {
      this.userCurrentPage = val;
      this.getUserManageData();
    },
    // 实现岗位角色列表分页
    roleHandleCurrentChange(val) {
      this.roleCurrentPage = val;
      this.getroleManageData();
    },
    // 获取所有岗位角色数据
    getpostData() {
      this.loading = true;
      this.$axios.$post("/system/v1/platform/department/obtain").then(res => {
        if (res.data.message === "success.") {
          this.departmentOptions = res.data.data;
        }
      });
    },
    // 获取所有权限数据
    getroleData() {
      this.loading = true;
      this.$axios
        .$post("/system/v1/common/dict", {
          groupid: "backpower"
        })
        .then(res => {
          if (res.data.message === "success.") {
            // this.dashboardid = res.data.data[0].dictid;
            // let tempArr = res.data.data;
            // this.authorities = tempArr.slice(1);
            this.authorities = res.data.data;
          }
        });
    },

    // 显示添加对话框
    add() {
      this.manage = '新增';
      if (this.activeIndex === 1) {
        this.emptyUser();
        this.getAuthority("edit");
        this.addUserIsVisible = true;
      } else if (this.activeIndex === 0) {
        // this.emptyRole();
        // this.addRoleIsVisible = true;
        this.backBtn = true;
        this.AddPostShow = true;
        this.currentStatus = 1;
      }
    },
    // 显示编辑角色对话框
    editRole(row) {
      this.currentStatus = 2;
      this.backBtn = true;
      this.AddPostShow = true;
      this.allRolelist = row;
      // this.selectedRole = [];
      this.manage = '编辑';
      // this.addRoleIsVisible = true;
      // this.addRoleForm.departmentid = row.departmentid;
      // this.addRoleForm.department = row.department;
      // this.addRoleForm.position = row.position;
      // this.addRoleForm.rolelist = row.rolelist;
      // this.addRoleForm = row;
      for (let i = 0; i < row.rolelist.length; i++) {
        this.selectedRole.push(row.rolelist[i].permissionname);
		console.log(row);
      }
    },
    // 选择岗位角色权限
    handClick(name, id) {
      let roleObj = {};
      roleObj.permissionid = id;
      if (!this.addRoleForm.rolelist.length) {
        this.addRoleForm.rolelist.push(roleObj);
      } else {
        var flag = true;
        for (let i = 0; i < this.addRoleForm.rolelist.length; i++) {
          if (id === this.addRoleForm.rolelist[i].permissionid) {
            this.addRoleForm.rolelist.splice(i, 1);
            flag = false;
          }
        }
        if (flag) {
          this.addRoleForm.rolelist.push(roleObj);
        }
      }

      if (this.selectedRole.indexOf(name) >= 0) {
        this.selectedRole.splice(this.selectedRole.indexOf(name), 1);
      } else {
        this.selectedRole.push(name);
      }
    },
    // 关闭新增/修改岗位角色对话框
    handleCloseRoleDialog() {
      if (this.manage === "新增") {
        this.emptyRole();
      }
    },
    // 取消新增/修改岗位角色对话框
    cancleRoleDialog() {
      this.addRoleIsVisible = false;
      if (this.manage === "新增") {
        this.emptyRole();
      }
    },
    // 新增/修改岗位角色
    // submitRoleForm() {
    //   if (this.addRoleForm.rolelist.length !== 0 && this.addRoleForm.department && this.addRoleForm.position) {
    //     this.$confirm(`是否${this.manage}该角色?`, '提示', {
    //       confirmButtonText: '确定',
    //       cancelButtonText: '取消',
    //       type: 'warning'
    //     }).then(() => {
    //       // 默认添加概览权限
    //       // let tempObj = {
    //       //   permissionid: this.dashboardid
    //       // }
    //       // this.addRoleForm.rolelist.push(tempObj);
    //       this.$axios.$post('/system/v1/platform/department/insertAndUpdate', this.addRoleForm).then(res => {
    //         if (res.data.message === 'success.') {
    //           this.addRoleIsVisible = false;
    //           this.getroleManageData();
    //           this.getpostData();
    //           this.emptyRole();
    //           if (this.manage === '新增') {
    //             this.$message({
    //               message: '新增成功',
    //               type: 'success'
    //             });
    //           } else if (this.manage === '编辑') {
    //             this.$message({
    //               message: '编辑成功',
    //               type: 'success'
    //             });
    //           }
    //         } else {
    //           this.$message({
    //             message: res.data.message,
    //             type: 'warning'
    //           });
    //         }
    //       })
    //     }).catch(() => {
    //       this.$message({
    //         type: 'warning',
    //         message: '已取消该操作'
    //       });
    //     });
    //   } else {
    //     this.$message({
    //       message: '请填选相关信息',
    //       type: 'warning'
    //     });
    //   }
    // },
    // 删除当前岗位角色
    delRole(row) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          this.$axios
            .$post("/system/v1/platform/department/delete", {
              departmentid: row.departmentid
            })
            .then(res => {
              if (res.data.message === "success.") {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                if (
                  this.roleManageData.length === 1 &&
                  this.roleCurrentPage > 1
                ) {
                  this.roleCurrentPage = this.roleCurrentPage - 1;
                }
                this.getroleManageData();
                this.getpostData();
                this.getroleData();
              } else {
                this.$message({
                  message: res.data.message,
                  type: "warning"
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消删除"
          });
        });
    },

    // 清空岗位角色数据
    emptyRole() {
      this.addRoleForm.departmentid = "";
      this.addRoleForm.department = "";
      this.addRoleForm.position = "";
      this.addRoleForm.rolelist = [];
      this.selectedRole = [];
    },
    // 清空用户数据
    emptyUser() {
      this.addUserForm.acuserid = "";
      this.addUserForm.name = "";
      this.addUserForm.account = "";
      this.addUserForm.telnum = "";
      this.addUserForm.department = "";
      this.addUserForm.departmentid = "";
      this.level = "";
      this.addUserForm.citys = [];
      this.addUserForm.province = "";
      this.addUserForm.city = "";
      this.addUserForm.area = "";
    },

    // 重新选择部门时,清空岗位角色下拉框
    departmentHandChange() {
      this.addUserForm.departmentid = "";
    },

    handleChangeLevel(val) {
      this.addUserForm.province = "";
      this.addUserForm.city = "";
      this.addUserForm.area = "";
    },
    isvalidPhone(str) {
      // const reg = /(^1[3|4|5|7|8][0-9]\d{8}$)|(0\d{2,3}-\d{7,8})/
      const reg = /(^1[3-9][0-9]\d{8}$)|(^(0\d{2})-(\d{8})$)|(^(0\d{3})-(\d{7})$)|(^(0\d{2})-(\d{8})-(\d+)$)|(^(0\d{3})-(\d{7})-(\d+)$)/;
      return reg.test(str);
    },
    // checkTel(str) {
    //   const reg = /0\d{2,3}-\d{7,8}/
    //   return reg.test(str)
    // },
    // validate() {
    //   console.log(this.addUserForm.telnum);
    //   let str = this.addUserForm.telnum;
    //   if (!this.isvalidPhone(str)) {
    //     this.$message.warning("输入格式有误！");
    //     return;
    //   } else {
    //     if (!this.checkTel(str)) {
    //       this.$message.warning("输入格式有误！");
    //     }
    //   }
    // },
    // 新增/修改用户
    submitUserForm() {
      this.addUserForm.level = this.level;
      if (
        this.addUserForm.name &&
        this.addUserForm.account &&
        this.addUserForm.telnum &&
        this.addUserForm.departmentid &&
        this.addUserForm.level
      ) {
        let str = this.addUserForm.telnum;
        if (!this.isvalidPhone(str)) {
          this.$message.warning("联系电话输入格式有误！");
          return;
        }
        if (this.addUserForm.level !== "0" && !this.addUserForm.province) {
          this.$message({
            type: "warning",
            message: "请选择权限范围！"
          });
          return;
        }
        this.$confirm(`是否${this.manage}该用户?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$axios
              .$post(
                "/system/v1/platform/user/updateAndInsert",
                this.addUserForm
              )
              .then(res => {
                if (res.data.message === "success.") {
                  this.getUserManageData();
                  this.addUserIsVisible = false;
                  this.emptyUser();
                  if (this.manage === "新增") {
                    this.$message({
                      message: "新增成功",
                      type: "success"
                    });
                  } else if (this.manage === "编辑") {
                    this.$message({
                      message: "编辑成功",
                      type: "success"
                    });
                  }
                } else {
                  this.$message({
                    message: res.data.message,
                    type: "warning"
                  });
                }
              });
          })
          .catch(() => {
            this.$message({
              type: "warning",
              message: "已取消该操作"
            });
          });
      } else {
        this.$message({
          message: "请填选相关信息",
          type: "warning"
        });
      }
    },

    // 取消用户对话框,清空数据
    cancleUserDialog() {
      this.addUserIsVisible = false;
      if (this.manage === "新增") {
        // this.editUser();
        this.emptyUser();
      }
    },

    // 关闭用户对话框,清空数据
    handleCloseUserDialog() {
      // this.addUserIsVisible = false;
      if (this.manage === "新增") {
        this.emptyUser();
      }
    },

    handleClick(tab, event) {},

    // 重置当前用户密码
    resetPassword(row) {
      this.$confirm("此操作将重置该用户密码, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          this.$axios
            .$post("/system/v1/platform/user/reset", {
              acuserid: row.userid
            })
            .then(res => {
              if (res.data.message === "success.") {
                this.$message({
                  type: "success",
                  message: "重置成功!"
                });
              } else {
                this.$message({
                  type: "warning",
                  message: "重置失败,请联系管理员"
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消删除"
          });
        });
    },

    // 编辑当前用户
    editUser(row) {
      this.manage = "编辑";
      this.addUserForm.acuserid = row.userid || "";
      this.addUserForm.name = row.name;
      this.addUserForm.telnum = row.telnum;
      this.addUserForm.departmentid = row.departmentid;
      this.addUserForm.account = row.account;
      this.addUserForm.department = row.department;
      this.addUserIsVisible = true;
      this.level = row.level;
      this.addUserForm.province = row.province || "";
      this.addUserForm.city = row.city || "";
      this.addUserForm.area = row.area || "";
      this.addUserForm.citys = [];
      row.province && this.addUserForm.citys.push(+row.province);
      row.city && this.addUserForm.citys.push(+row.city);
      row.area && this.addUserForm.citys.push(+row.area);
    },
    // 删除当前用户
    delUser(row) {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      })
        .then(() => {
          this.$axios
            .$post("/system/v1/platform/user/delete", {
              acuserid: row.userid
            })
            .then(res => {
              if (res.data.code === 1) {
                this.$message({
                  type: "success",
                  message: "删除成功!"
                });
                if (
                  this.userManageData.length === 1 &&
                  this.userCurrentPage > 1
                ) {
                  this.userCurrentPage = this.userCurrentPage - 1;
                }
                this.getUserManageData();
              } else {
                this.$message({
                  type: "warning",
                  message: res.data.message
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "warning",
            message: "已取消删除"
          });
        });
    },

    //改变show状态
    onchangeShow(index) {
      this.show = false;
      this.backBtn = true;
    },
    // 选择城市
    handleCityChange(val) {
      console.log(val)
      this.addUserForm.citys = val;
      this.addUserForm.province = val[0];
      this.addUserForm.city = val[1];
      this.addUserForm.area = val[2];
    },
    //返回
    goBack() {
      this.show = true;
      this.backBtn = false;
      this.AddPostShow = false;
      this.getroleManageData();
    },
    handleSizeChange1(val) {
      this.userPageSize = val;
      this.userCurrentPage = 1;
      this.getUserManageData();
    },
    handleSizeChange2(val) {
      this.rolePageSize = val;
      this.roleCurrentPage = 1;
      this.getroleManageData();
    },
    getAuthority(type) {
      let userinfo = localStorage.getItem("userinfo");
      userinfo = JSON.parse(userinfo);
      this.level = userinfo.level;
      if (!type) {
        this.roleLevelOptions = this.roleLevelOptions.splice(
          this.level,
          this.roleLevelOptions.length
        );
      }
      this.addUserForm.province = +userinfo.province || "";
      this.addUserForm.city = +userinfo.city || "";
      this.addUserForm.area = +userinfo.area || "";
      this.addUserForm.citys = [];
      this.addUserForm.citys.push(+userinfo.province);
      this.addUserForm.citys.push(+userinfo.city);
      this.addUserForm.citys.push(+userinfo.area);
    }
  },
  watch: {
    level(newVal, oldVal) {
      // this.getAuthority();
      if (newVal == "0") {
        this.addUserForm.citys = ["全国"];
      }
    }
  }
};
